<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="800px"
      append-to-body
      custom-class="import-dialog"
      @close="close"
    >
      <div class="form-box">
        <el-form :model="form" :rules="rules" ref="form" class="add-form">
          <el-descriptions title="租住信息" :column="2">
            <el-descriptions-item label="房源">{{
                form.premisesAddress
              }}
            </el-descriptions-item>
            <el-descriptions-item label="租住周期">
              {{ form.checkInTime | formatDate('YYYY-MM-DD') }}
              至
              {{ form.checkOutTime | formatDate('YYYY-MM-DD') }}
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions title="退住信息"></el-descriptions>
          <el-form-item label="退租日期" prop="realityCheckOutTime">
            <el-date-picker
              value-format="yyyy-MM-dd HH:ss:mm"
              v-model="form.realityCheckOutTime"
              type="date"
              placeholder="选择日期"
              @change="checkOutTimeChange"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import formRule from '@/utils/formRule.js'
import { listPayType } from '@/api/house/unmount'
import { getOrderInfo, refundRent } from '@/api/order/order'
import { formatDate } from '@/utils/common/time'
import { debounce } from '@/utils'

export default {
  name: 'outOrder',
  dicts: [],
  components: {},
  props: {
    title: {
      default: '退租'
    },
    value: {
      default: false
    },
    orderId: {
      default: undefined
    },
    isDetail: {
      default: false
    },
    success: {
      type: Function,
      default: () => {
      }
    }
  },
  data() {
    return {
      // visible: false,
      dialogSelectHouseVisible: false,
      form: {
        orderId: '',
        orderState: '1',
        orderTab: '1',
        reserveUser: '张三', //预订人
        reserveUserPhone: '18570467877', //预订人手机号
        deptId: 103,
        checkInTime: '2024-03-05 17:55:00', //入住时间
        checkOutTime: '2024-04-11 17:55:00', //退房时间
        realityCheckInTime: null,
        realityCheckOutTime: null,
        finallySignTime: '2024-03-06 17:50:21',
        rentPaidNumber: 1, //已付租金
        depositPaidNumber: 1, //已付押金
        orderSource: '1', //订单来源
        orderType: '1', //订单类型
        tradingMode: '1', //成交方式
        linkedOrderId: null,
        freeRentNumber: null, //免租天数
        rentalMode: '1', //租赁方式
        depositNumber: 1, //押几
        payNumber: 1, //付几
        deposit: null, //押金
        monthRent: null, //月租金
        totalRent: null, //总租金
        memberNumber: 0,
        period: [],
        orderLessee: {
          lesseeType: '1', //承租人类型：1个人 2企业
          lesseeName: '', //承租人姓名
          cardNumber: '', //身份证号
          enterpriseName: '', //企业名称
          phone: '', //手机号
          USCC: '', //社会统一信用代码
          cardImgsList: [
            'https://saas-v5.oss-cn-guangzhou.aliyuncs.com/saas-admin/druid/saas-v5/1712565698019newhxk.jpg'
          ] //证件照片
        }
      },
      areaCalculateState: false,
      //收费项
      chargeItemForm: {
        chargeItemArr: []
      },

      chargeItemList: [],
      chargeItemSelected: [],
      pickerOptions: {
        disabledDate: (time) => {
          return (
            // time.getTime() < new Date(this.form.checkInTime) || time.getTime() > new Date(this.form.checkOutTime)
            time.getTime() < new Date(this.form.checkInTime) || time.getTime() > new Date(this.form.checkOutTime)
          )
        }
      },
      rules: {
        realityCheckOutTime: [
          { required: true, message: '请选择退租日期', trigger: 'change' }
        ],
        ['orderLessee.phone']: [
          { required: true, message: '请输入手机', trigger: 'blur' }
        ],
        tenantType: [
          { required: true, message: '请选择身份', trigger: 'blur' }
        ],
        enterpriseName: [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '请输入法人信息', trigger: 'blur' }
        ],
        socialCreditNumber: [
          {
            required: true,
            message: '请输入统一社会信用代码',
            trigger: 'blur'
          }
        ],
        freeRentNumber: [
          {
            required: true,
            message: '请输入免租天数',
            trigger: 'blur'
          }
        ],
        monthRent: [
          {
            required: true,
            message: '请输入月租金',
            trigger: 'blur'
          }
        ],
        deposit: [
          {
            required: true,
            message: '请输入押金',
            trigger: 'blur'
          }
        ],
        ['orderLessee.lesseeName']: [
          {
            required: true,
            message: '请输入姓名',
            trigger: ['change', 'blur']
          }
        ],
        ['orderLessee.phone']: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          {
            validator: formRule.phone,
            message: '',
            trigger: ['change', 'blur']
          }
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        ['orderLessee.cardNumber']: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          {
            validator: formRule.IDCard,
            message: '',
            trigger: ['change', 'blur']
          }
        ],

        period: [
          {
            required: true,
            type: 'array',
            message: '请选择日期',
            trigger: 'change'
          }
        ],
        ['orderLessee.lesseeType']: [
          { required: true, message: '请选择签约方式', trigger: 'change' }
        ],
        checkInTime: [
          { required: true, message: '请输入入住日期', trigger: 'blur' }
        ],
        checkOutTime: [
          { required: true, message: '请输入退房日期', trigger: 'blur' }
        ],
        finallySignTime: [
          { required: true, message: '请选择最晚签约日期', trigger: 'blur' }
        ],
        paymentType: [
          { required: true, message: '请选择付款方式', trigger: 'blur' }
        ],
        payTypeId: [
          { required: true, message: '请选择押付方式', trigger: 'change' }
        ],
        cleaningType: [
          {
            required: true,
            message: '请选择是否购买保洁费',
            trigger: 'change'
          }
        ],
        cleaningPrice: [
          { required: true, message: '请输入保洁费', trigger: 'blur' }
        ],
        priceAmounts: [
          { required: true, message: '请输入总金额', trigger: 'blur' }
        ],
        depositPaidNumber: [
          { required: true, message: '请输入押金', trigger: 'blur' }
        ],
        rentPaidNumber: [
          { required: true, message: '请输入租金', trigger: 'blur' }
        ],
        billingDate: [
          { required: true, message: '请输入号数', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    visible:{
      get(){
        return this.value
      },
      set(val){
        this.$emit('input', val)
      }
    },
    customHouseName: {
      get() {
        return this.form.houseId
          ? this.form.estateName +
          this.form.buildingName +
          '栋' +
          this.form.unitName +
          '单元' +
          this.form.roomNumber
          : ''
      },
      set() {
      }
    }
  },
  watch: {
    value:{
      handler(newVal, oldVal) {
        if (newVal) {
          this.init()
        }
      },
      deep: true,
      immediate: true
    },
  },
  methods: {
    init() {
      //重置
      //this.reset();
      this.getInfo()
    },
    //日期更改
    periodChange(e) {
      this.form.checkInTime = e[0] + ' 00:00:00'
      this.form.checkOutTime = e[1] + ' 23:59:00'
    },
    finallySignChange(e) {
      this.form.finallySignTime = e + ' 23:59:00'
    },
    //重置表单
    reset() {
      this.form = this.$options.data().form
    },
    //获取详情
    getInfo() {
      if (!this.orderId) return
      getOrderInfo(this.orderId).then((response) => {
        this.form = response.data

        this.form['realityCheckOutTime'] = null
      })
    },
    //获取押付方式
    getListPayType() {
      listPayType().then((response) => {
        this.payTypeList = response.data
      })
    },
    //移除收费项
    removeChargeItem(index) {
      this.chargeItemSelected.splice(index, 1)
    },
    //关闭收费项弹窗
    closeChargeItemDialog() {
    },
    //面积计算租金状态改变
    changeAreaCalculateState(data) {
      console.log('data', data)
      let value = data ? '1' : '0'
      this.$set(this.form, 'areaCalculateState', value)
    },

    //房间选择回调
    selectHouseCb(data) {
      let houseObj = {
        houseId: '', //房屋id
        premisesAddress: null //小区地址
      }
      for (const key in houseObj) {
        houseObj[key] = data[key]
      }
      this.form = { ...this.form, ...houseObj }
    },
    //移除设备
    removeFacility(item, index) {
      this.form.houseFacilitiesItemList.splice(index, 1)
    },
    checkOutTimeChange(data) {
      console.log('data', data)
    },
    //提交表单
    submitForm: debounce(function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 判断退租日期是否在开始-结束日期内（开始日期<选择日期＜结束日期）
          // let startTime = new Date(this.form.checkInTime)
          // let endTime = new Date(this.form.checkOutTime)
          // let realityCheckOutTime = new Date(this.form.realityCheckOutTime)
          let startTime = this.$moment(this.form.checkInTime).valueOf()
          let endTime = this.$moment(this.form.checkOutTime).valueOf()
          let realityCheckOutTime = this.$moment(this.form.realityCheckOutTime).valueOf()
          if (startTime > realityCheckOutTime || realityCheckOutTime > endTime) {
            this.$message.error('退租日期需在租住周期内')
            return
          }
          refundRent(this.form).then((response) => {
            this.$emit('success')
            this.$message.success('退租成功')
            this.visible = false
          })
        }
      })
    }, 300),
    //关闭
    close() {
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.import-dialog {
  height: auto;
  max-height: 80vh;
  overflow-y: auto;

  .dialog-footer {
    text-align: center;
  }
}

::v-deep .el-dialog__body {
  max-height: 80vh !important;
  overflow-y: auto;
}

.form-box {
  .tabs {
    display: flex;

    .tabs-item {
      padding: 0 10px;
      height: 40px;
      line-height: 40px;
      font-size: 16px;
      position: relative;
      cursor: pointer;

      &::before {
        content: "";
        position: absolute;
        left: 50%;
        bottom: -2px;
        width: 0;
        height: 2px;
        opacity: 0;
        background: #0caaf0;
        transition: all 0.3s;
      }

      &.active {
        color: #0caaf0;

        &::before {
          opacity: 1;
          left: 0;
          width: 100%;
        }

        cursor: default;
      }
    }
  }

  .add-form {
    .section {
      .label {
        display: flex;
        margin-bottom: 20px;
        font-size: 16px;
        align-items: center;
        color: #303133;

        label {
          display: block;
          width: 80px;

          &.dot::before {
            content: "*";
            color: #ff4949;
            margin-right: 4px;
          }
        }

        .icon {
          color: #02a7f0;
          font-size: 30px;
          margin-left: 30px;
          cursor: pointer;
        }
      }

      .tips {
        color: #aaaaaa;
      }

      .custom-formItem-lable {
        display: flex;
        align-items: center;

        .handle-icon {
          color: #02a7f0;
          font-size: 30px;
          margin-left: 30px;
          cursor: pointer;
        }
      }

      .handle-icon {
        color: #02a7f0;
        font-size: 30px;
        cursor: pointer;
      }
    }
  }
}
</style>
